package odgs.app.notuse;

import java.util.Enumeration;
import java.util.List;

import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;

import odgs.Directory;
import odgs.Explorer;
import odgs.ExplorerNode;
import odgs.listener.ExplorerListener;

public class ExplorerTreeModel extends DefaultTreeModel implements ExplorerListener
{
	private ExplorerNode root;
	private Explorer explorer;
	
	public ExplorerTreeModel(Explorer explorer)
	{
		super(new ExplorerTreeNode(explorer.getRoot()));
		this.explorer = explorer; 
		root = explorer.getRoot();
		explorer.addExplorerModifyListener(this);
	}

	public void added(ExplorerNode parent, ExplorerNode node)
	{
		reload();
	}

	public void copied(ExplorerNode node)
	{
		reload();
	}

	public void modified(ExplorerNode node)
	{
		reload();
	}

	public void moved(ExplorerNode node)
	{
		reload();
	}

	public void removed(ExplorerNode parent, ExplorerNode node)
	{
		reload();
	}

	public void setedPosition(String position)
	{
		
		System.out.println(position);
	}

	public void setPosition(String position)
	{
		explorer.setPosition(position);
	}
}

class ExplorerTreeNode implements TreeNode
{
	private ExplorerNode node;
	private ExplorerNode parent;
	
	public ExplorerTreeNode(ExplorerNode root)
	{
		node = root;
	}

	public ExplorerTreeNode(ExplorerNode parent, ExplorerNode node)
	{
		this.node = node;
		this.parent = parent;
	}

	public Enumeration children()
	{
		if(node.canChildren())
		{
			final List<Directory> nodes = ((Directory)node).getDirectorys();
			return new Enumeration()
			{
				int i = 0;
				public boolean hasMoreElements()
				{
					return i < nodes.size();
				}

				public Object nextElement()
				{
					return nodes.get(i++);
				}
			};
		}
		return new Enumeration()
		{
			public boolean hasMoreElements()
			{
				return false;
			}

			public Object nextElement()
			{
				return null;
			}
		};
	}

	public boolean getAllowsChildren()
	{
		return node.canChildren();
	}

	public TreeNode getChildAt(int index)
	{
		return new ExplorerTreeNode(node, ((Directory)node).getDirectory(index));
	}

	public int getChildCount()
	{
		return ((Directory)node).getDirectorySize();
	}

	public int getIndex(TreeNode arg0)
	{
		return 0;
	}

	public TreeNode getParent()
	{
		return new ExplorerTreeNode(parent);
	}

	public boolean isLeaf()
	{
		return !node.canChildren();
	}
	
	@Override
	public String toString()
	{
		return node.getName();
	}

	public String getPath()
	{
		return node.getPath();
	}

	public String getName()
	{
		return node.getName();
	}
}